<template>
  <div style="width: auto; height: 400px" :id="id"></div>
</template>


<script>
export default {
  data() {
    return {
      myChart: null,
    };
  },

  methods: {
    getDataArrayIsEmpty() {
      let value = 0;
      if (this.data) {
        this.data.forEach((val) => {
          value += val;
        });
      }
      return value == 0 ? false : true;
    },
    getData() {
      if (this.getDataArrayIsEmpty()) {
        var i = [];
        for (var index = 0; index < this.label.length; index++) {
          i[index] = { value: this.data[index], name: this.label[index] };
        }
        return i;
      }
      return [{ value: 0, name: "无数据" }];
    },
    reDrawEchats() {
      var that = this;
     
      var echartsOption = {
        // echarts选项，所有绘图数据和样式都在这里设置
        tooltip: {
          //鼠标放到图上的数据展示样式
          trigger: "item",
          formatter: this.title + " <br/>{b} : {c} ({d}%)",
          textStyle: {
            fontSize: "100%", //字体大小
          },
        },

        legend: {
          orient: "vertical",
          left: "80%", //图例距离左的距离
          y: "center", //图例上下居中
          itemGap: 30,
          itemWidth: 25,
          padding: 10,
          textStyle: {
            fontSize: "100%",
          },
        },
        series: [
          {
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
            },
            emphasis: {
              label: {
                show: false,
              },
            },
            labelLine: {
              show: false,
            },
            itemStyle: {
              normal: {
                color: function (params) {
                  return that.getDataArrayIsEmpty()
                    ? that.color[params.dataIndex]
                    : that.color[0];
                },
              },
            },

            data: this.getData(),
          },
        ],
      };

      this.myChart.setOption(echartsOption);
    },
  },

  mounted() {
    var echarts = require("echarts");
    this.$nextTick(() => {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(this.id));
      // 绘制图表
      this.myChart = myChart;
      this.reDrawEchats();
      setTimeout(() => {
        myChart.resize();
      }, 0)
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    });
  },
  watch: {
    data(val) {
      this.data = val;
      this.reDrawEchats();
    },
    color(val) {
      this.color = val;
      this.reDrawEchats();
    },
    label(val) {
      this.label = val;
      this.reDrawEchats();
    },
  },
  props: {
    data: {
      type: Array,
    },
    title: {
      type: String,
    },
    id: {
      type: String,
    },
    color: {
      type: Array,
    },
    label: {
      type: Array,
    },
  },
};
</script>